package org.lilred.nzbberry.plugin;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;

import javax.microedition.io.HttpConnection;

import org.lilred.nzbberry.controllers.PluginController;
import org.lilred.nzbberry.http.HttpMultipartRequest;
import org.lilred.nzbberry.webservice.SabnzbdClient;

import net.rim.device.api.browser.plugin.BrowserContentProviderContext;
import net.rim.device.api.util.StringUtilities;

public class PluginDownloader extends GivesProgress {
	PluginController controller;
	BrowserContentProviderContext context;
	public int state;

	public PluginDownloader(PluginController controller, BrowserContentProviderContext context) {
		this.controller = controller;
		this.context = context;
		state = READY;
	}

	public void run() {
		try {
			state = CONNECTING;
			HttpConnection conn = context.getHttpConnection();
			InputStream responseData = context.getInputStream();
			state = GETTING_FILESIZE;
			int length = (int) conn.getLength();
			if (length == -1) state = UNKNOWN_FILESIZE;
			else state = TRANSFERRING;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			byte[] buffer = new byte[10000];
			int bytesRead = responseData.read(buffer);
			int totalBytes = 0;
			while (bytesRead > 0) {
				baos.write(buffer, 0, bytesRead);
				bytesRead = responseData.read(buffer);
				totalBytes += bytesRead;
			}
			baos.close();
			String disposition = conn.getHeaderField("Content-Disposition");
			int start = disposition.indexOf("=") + 1;
			String filename = disposition.substring(start);
			filename = StringUtilities.removeChars(filename, "\"");
			if (disposition.indexOf(".nzb") == -1) throw new Exception("nzbBerry tried to open this URL because it looked like an nzb. However, the content-disposition header of the file indicates that it is not.  If this error is preventing you from downloading a file that you need, please uninstall nzbBerry."); 
			String contentType = conn.getHeaderField("Content-type");
			conn.close();
			state = COMPLETE;
			HttpMultipartRequest multipartRequest = new HttpMultipartRequest(SabnzbdClient.getApiUrl("addfile"), new Hashtable(), "nzbfile", filename, contentType, baos.toByteArray());
			controller.downloadComplete(multipartRequest);
		} catch (Exception e) {
			state = ERROR;
		}
	}
	

}
